<template>
  <div
    :class="['pull-refresh',{ 'down': (state===1),'toload': (state===2),'loading': (state===3),'loaded': (state===4) }]"
    @touchstart="touchStart($event)"
    @touchmove="touchMove($event)" @touchend="touchEnd($event)">
    <div class="pulldown">下拉刷新排行榜数据</div>
    <div class="toload">松开加载排行榜数据</div>
    <div class="load_date">
      <loading></loading>
    </div>
    <div class="finish">排行榜已刷新</div>

    <div class="bodyer" :style="{ transform: 'translate3d(0, ' + moveY + 'px, 0)' }">
      <slot></slot>
    </div>
  </div>
</template>
<script>
  import './pull-refresh.scss';
  import loading from './loading';

  export default {
    name: 'pullrefresh',
    components: {
      loading
    },
    props: {
      //数据刷新的回调函数
      onRefresh: {
        type: Function,
        required: true
      }
    },
    data() {
      return {
        state: 0, //当前状态
        loading: false, //是否真正请求数据
        startY: 0,
        moveY: 0
      }
    },
    methods: {
      touchStart({
                   targetTouches: [touch]
                 } = e) {
        this.startY = touch.pageY;
      },
      touchMove({
                  targetTouches: [touch]
                } = e) {
        event.preventDefault();
        event.stopPropagation();
        //向上滑动忽略
        if (touch.pageY <= this.startY) {
          return;
        }
        if (!this.loading) {
          this.state = 1;
        }

        this.moveY = Math.pow(touch.pageY - this.startY, 0.8);
        if (this.moveY > 50 && !this.loading) {
          this.state = 2;
        } else {
          this.state = 1;
        }
      },
      touchEnd() {
        if (this.state === 2) {
          this.state = 3;
          this.loading = true;
          this.moveY = 20;
          this.onRefresh(this.refreshDone);
        } else {
          this.state = 0;
          this.initStatus();
        }
      },
      refreshDone() {
        setTimeout(() => {
          this.state = 4;
          setTimeout(() => {
            this.state = 0;
          }, 500);
          this.initStatus();
        }, 1500)
      },
      initStatus() {
        this.loading = false;
        this.startY = 0;
        this.moveY = 0;
      }
    }
  }
</script>
